"use strict";
module.exports = (options = { canCreateTables: false }) => {
    return new Promise((resolve, reject) => {
        let envConf = require('../../../config/env');
        console.log('spy', `get database config...${JSON.stringify(envConf)}`);
        var fs = require("fs");
        var path = require("path");
        let mysqlConf = envConf.mysql;
        let Sequelize = require('sequelize');
        var sequelize = new Sequelize(mysqlConf.schema, mysqlConf.username, mysqlConf.password, {
            host: mysqlConf.host,
            dialect: 'mysql',
            pool: {
                max: mysqlConf.pool.max,
                min: mysqlConf.pool.min,
                idle: mysqlConf.pool.idle,
            },
            logging: function(sql) {
                
            }
        });

        var db = {};
        var modelNameOrders = [];
        require('./loadOrders.json')
            .forEach(function (file) {
                var model = sequelize.import(path.join(__dirname, `${file}.js`));
                db[model.name] = model;
                modelNameOrders.push(model.name);
            });

        modelNameOrders.forEach(function (modelName) {
            if ("associate" in db[modelName]) {
                db[modelName].associate(db);
            }
        });

        if (options.canCreateTables) {
            sequelize.sync();
        }

        db.sequelize = sequelize;
        db.Sequelize = Sequelize;

        resolve(db);
    });
};